import axios from 'axios'
import { notification } from 'antd'

import { BASE_URL } from '../CONST'

const myAxios = axios.create({
    baseURL: BASE_URL,
})


// 请求拦截器
myAxios.interceptors.request.use(req => {
    const token = localStorage.getItem('token')
    req.headers['x-auth-token'] = token
    return req
}, err => {
    return Promise.reject(err)
})

// 响应拦截器
myAxios.interceptors.response.use(res => {
    console.log('返回的数据', res);
    if (res.headers['x-auth-token']) {
        localStorage.token = res.headers['x-auth-token']
    }
    return res.data
}, err => {
    const response = err.response
    if (response) {
        switch (response.status) {
            case 401:
                notification.error({ message: '请先登录' });
                localStorage.removeItem('token')
                localStorage.removeItem('userInfo')
                window.location.hash = '#/login'
                break;
            case 404:
                break;
            case 500:
                notification.error({ message: '服务器bengle' })
                break;
            default: break
        }
    }
    return Promise.reject(err)
})

export default myAxios